import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: ''
  }),
  getters: {
    getToken: (state) => state.token
  },
  actions: {
    setToken (newToken) {
      this.token = newToken
    },
    removeToken () {
      this.token = ''
    }
  },
  persist: true
})

export const useMusicPlayerStore = defineStore('musicPlayer', {
  state: () => ({
    isPlaying: false,
    audio: null,
    src: '/assets/ziwo.ogg',
    volume: 50,
    currentTime: 0,
    duration: 0
  }),
  actions: {
    getSupportedSrc() {
      const audio = document.createElement('audio')
      if (audio.canPlayType('audio/ogg')) {
        return '/assets/ziwo.ogg'
      } else {
        return '/assets/ziwo.mp3'
      }
    },
    playMusic() {
      if (!this.audio) {
        this.src = this.getSupportedSrc()
        this.audio = new Audio(this.src)
        this.audio.loop = true
        this.audio.volume = this.volume / 100
        this.audio.addEventListener('timeupdate', () => {
          this.currentTime = this.audio.currentTime
          this.duration = this.audio.duration
        })
      }
      this.audio.play()
      this.isPlaying = true
    },
    pauseMusic() {
      if (this.audio) {
        this.audio.pause()
        this.isPlaying = false
      }
    },
    stopMusic() {
      if (this.audio) {
        this.audio.pause()
        this.audio.currentTime = 0
        this.isPlaying = false
      }
    },
    setVolume(val) {
      this.volume = val
      if (this.audio) this.audio.volume = val / 100
    },
    setCurrentTime(val) {
      if (this.audio) this.audio.currentTime = val
      this.currentTime = val
    }
  }
})